'''
Created on Jun 9, 2011

@author: Igor
'''

from lib.dbobjects import Athlete, Stats, Explanation, RESULTS_DISPLAYED, \
        ATHLETES_STORED, DAILY_BUDGET
from auctions.cpc_auction import cpc_top_athletes
from auctions.cr_auction import cr_top_athletes
from auctions.ctr_auction import ctr_top_athletes

import os
import random

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

POSITION_CTRS = [0.500, 0.1708, 0.0950, 0.0631, 0.0416, 0.0319, 0.0256, 0.0213, 0.0180, 
                         0.0162, 0.0165]

THRESHOLD_IMPRESSIONS = 100

# NOTE: This is where you change the auction logic
def calculate_top_athletes(stats):
    return cr_top_athletes(stats)
    #return ctr_top_athletes(stats)
    #return cpc_top_athletes(stats)

def populate_athletes():
    list = ["Tiger Woods", "Michael Jordan", "Hank Aaron", "Wayne Gretzky",
            "Muhammad Ali", "Pele", "Lance Armstrong", "Peyton Manning",
            "Roger Federer", "Michael Phelps"]
    cpcs = [25, 20, 20, 18, 18, 18, 16, 14, 12, 11]
    assert len(list) == ATHLETES_STORED
    for i in xrange(ATHLETES_STORED):
        athlete = Athlete(id=i+1, name=list[i], cpc=cpcs[i])
        athlete.put()

def set_popularity(stats):
    # The None of These has popularity 1.00
    stats.popularity[0] = 1.00
    for i in xrange(ATHLETES_STORED):
        stats.popularity[i+1] = 0.50 + random.random()
    stats.popularity_set = True
        
def run_queries(stats, number_votes):
    if not stats.popularity_set:
        set_popularity(stats)

    for _ in xrange(number_votes):
        # Generate choices
        ids = calculate_top_athletes(stats)
    
        # Make a choice
        cum_sums = [POSITION_CTRS[0]]
        for i in xrange(RESULTS_DISPLAYED):
            cum_sums.append(cum_sums[i] + POSITION_CTRS[i+1] *
                            stats.popularity[ids[i]])
        rand_float = random.uniform(0, cum_sums[RESULTS_DISPLAYED])
        i = 0
        while cum_sums[i] < rand_float:
            i += 1
        winner_position = i
    
        # Record the choice
        stats.searches += 1  
        for i in xrange(RESULTS_DISPLAYED):
            athlete = Athlete.all().filter("id =", ids[i]).get()
            athlete.impressions[i] += 1
            athlete.ec += POSITION_CTRS[i+1]
            # Check if the threshold was reached
            impressions = sum(athlete.impressions)
            if impressions >= THRESHOLD_IMPRESSIONS:
                athlete.new = False
            if i == winner_position - 1:
                stats.clicks[i] += 1
                athlete.clicks[i] += 1
                athlete.amount_paid += stats.costs[i]
                if athlete.amount_paid >= DAILY_BUDGET:
                        athlete.out_of_budget = True
                stats.profit += stats.costs[i]
            athlete.put()
        if winner_position == 0:
            # None was selected
            stats.clicks[RESULTS_DISPLAYED] += 1
    stats.put()

## @details This class helps perform the things that are useful for all the pages
class BaseRequestHandler(webapp.RequestHandler):
    def generate(self, template_name, template_values={}, links=[]):
        
        # Get all the profilers sorted by date last modified
        athletes_query = Athlete.all().order('-cpc')
        athlete = athletes_query.get()
        if athlete is None:
            populate_athletes()
            athletes_query = Athlete.all().order('-cpc')
        athletes = athletes_query.fetch(ATHLETES_STORED)
        stats = Stats.all().get()
        explanation = Explanation.all().get()
        
        # For now, always empty the links and games
        links = []
        # Links contain all the links we want to display at the bottom
        links.append([users.create_logout_url('/'), 'Logout'])
        welcome_message = "Who do you think is the best male athlete of all times?"
        
        values = {
            'user': users.get_current_user(),
            'application_name': 'Top Athlete',
            'links': links,
            'welcome_message': welcome_message,
            'athletes': athletes,
            'stats': stats,
            'explanation': explanation
        }
        values.update(template_values)
        directory = os.path.dirname(__file__)
        path = os.path.join(directory, os.path.join('htmls', template_name))
        self.response.out.write(template.render(path, values))